import {FC} from "react";
import {useLocation, Navigate} from "react-router-dom";
import {Spin} from "antd";
import {useAppSelector} from "@/app/hooks";
import {selectUser} from "@pages/Login/slice";

function withAuthorization(WrappedComponent: FC) {
    return () => {
        const {token, name} = useAppSelector(selectUser);
        
        // 获取当前路由地址
        const {pathname} = useLocation();
        
        if (token) {
            // 说明登录过
            if (pathname === "/login" || pathname === "/") {
                return <Navigate to="/mkbk/home"/>;
            }
            // 说明访问不能登录页面或/
            // 判断是否有用户数据
            if (name) {
                return <WrappedComponent/>;
            }
            
            return <Spin size="large"/>;
        } else {
            // 说明没有登录过
            if (pathname === "/login") {
                return <WrappedComponent/>;
            }
            
            // 说明访问不是登录页面
            return <Navigate to="/login"/>;
        }
    };
    
}

export default withAuthorization;
